package com.vegetable.modules.service.finance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.finance.PaymentLog;
import com.vegetable.modules.entity.finance.PaymentPurchase;
import com.vegetable.modules.entity.wx.WXApproval;
import com.vegetable.modules.mapper.finance.PaymentPurchaseMapper;
import com.vegetable.modules.service.finance.IPaymentLogService;
import com.vegetable.modules.service.finance.ManualPaymentService;
import com.vegetable.modules.service.finance.UnionPayService;
import com.vegetable.modules.service.wx.WXApprovalService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.WxCpApprovalDetailResult;
import me.chanjar.weixin.cp.bean.oa.applydata.ApplyDataContent;
import me.chanjar.weixin.cp.bean.oa.applydata.ContentValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 手动支付服务实现类
 *
 * @author Qoder
 */
@Slf4j
@Service
public class ManualPaymentServiceImpl implements ManualPaymentService {

    @Autowired
    private PaymentPurchaseMapper paymentPurchaseMapper;

    @Autowired
    private UnionPayService unionPayService;

    @Autowired
    private IPaymentLogService paymentLogService;

    @Autowired
    private WxCpService wxCpService;
    
    @Autowired
    private WXApprovalService wxApprovalService;
    
    @Value("${wechat.cp.admin.userIds:XiaoQin18754420999}")
    private String adminUserIds;
    
    @Autowired
    private com.vegetable.modules.service.wx.config.WxApprovalConfig wxApprovalConfig;

    @Override
    public R executeManualPayment(Long paymentId) {
        try {
            log.info("开始执行手动支付，付款ID: {}", paymentId);

            // 获取付款详情
            PaymentPurchase payment = paymentPurchaseMapper.selectById(paymentId);
            if (payment == null) {
                return R.fail("付款记录不存在");
            }

            // 检查付款状态
            if (payment.getApprovalState() == null || payment.getApprovalState() != 2) {
                return R.fail("付款审批状态不正确，当前审批状态: " + payment.getApprovalState() + "，只有审批通过的记录才能执行手动支付");
            }

            // 从审批记录中获取收款人信息
            String payeeName = payment.getCustomerName();
            String payeeBankAccount = "";
            String payeeBankName = "";
            
            try {
                // 查找关联的审批记录
                QueryWrapper<WXApproval> wrapper = new QueryWrapper<>();
                wrapper.eq("payment_id", paymentId);
                WXApproval wxApproval = wxApprovalService.getOne(wrapper);
                
                if (wxApproval != null) {
                    // 从企业微信获取审批详情
                    WxCpApprovalDetailResult detailResult = wxCpService.getOaService().getApprovalDetail(wxApproval.getSpNo());
                    if (detailResult != null && detailResult.getErrCode() == 0) {
                        WxCpApprovalDetailResult.WxCpApprovalDetail approvalInfo = detailResult.getInfo();
                        // 使用工具类提取收款人信息
                        Map<String, String> payeeInfo = WxApprovalPayeeInfoExtractor.extractPayeeInfo(approvalInfo);
                        payeeName = payeeInfo.get("payeeName");
                        payeeBankAccount = payeeInfo.get("payeeBankAccount");
                        payeeBankName = payeeInfo.get("payeeBankName");
                    }
                }
            } catch (WxErrorException e) {
                log.warn("从企业微信获取审批详情时发生异常", e);
            } catch (Exception e) {
                log.warn("解析审批详情中的收款人信息时发生异常", e);
            }

            // 执行支付，传递收款人信息
            R payResult = unionPayService.executeSinglePayment(
                payment, 
                payeeName, 
                payeeBankAccount, 
                payeeBankName
            );

            if (payResult.getCode() == 0) {
                // 支付成功
                payment.setState(1); // 1表示实际已付
                payment.setRemitTime(new Date()); // 设置打款时间
                paymentPurchaseMapper.updateById(payment);

                // 查找关联的审批记录并同步状态到企业微信
                try {
                    QueryWrapper<WXApproval> wrapper = new QueryWrapper<>();
                    wrapper.eq("payment_id", paymentId);
                    WXApproval wxApproval = wxApprovalService.getOne(wrapper);
                    
                    if (wxApproval != null) {
                        // 更新审批状态
                        wxApproval.setSpStatus("ALREADY_PAY");
                        wxApprovalService.updateById(wxApproval);
                        
                        // 同步状态到企业微信
                        boolean syncResult = wxApprovalService.syncApprovalStatusToWechat(wxApproval.getSpNo(), "ALREADY_PAY");
                        if (!syncResult) {
                            log.warn("同步审批状态到企业微信失败，审批编号: {}", wxApproval.getSpNo());
                        }
                    }
                } catch (Exception e) {
                    log.warn("同步审批状态时发生异常", e);
                }

                // 发送通知给相关人员
                // notifyApplicant(payment, "手动支付已完成", true);

                log.info("手动支付成功，付款ID: {}", paymentId);
                return R.success("手动支付成功");
            } else {
                // 支付失败
                payment.setState(1); // 1表示实际已付（但支付失败）
                paymentPurchaseMapper.updateById(payment);

                // 发送通知给相关人员
                // notifyApplicant(payment, "手动支付失败: " + payResult.getMsg(), false);

                log.error("手动支付失败，付款ID: {}, 错误信息: {}", paymentId, payResult.getMsg());
                return R.fail("手动支付失败: " + payResult.getMsg());
            }
        } catch (Exception e) {
            log.error("执行手动支付时发生异常", e);
            return R.fail("手动支付异常: " + e.getMessage());
        }
    }
    
    /**
     * 执行手动支付（包含收款人信息）
     *
     * @param paymentId 付款ID
     * @param payeeName 收款人全称
     * @param payeeBankAccount 收款人银行账号
     * @param payeeBankName 收款人开户行
     * @return 支付结果
     */
    public R executeManualPayment(Long paymentId, String payeeName, String payeeBankAccount, String payeeBankName) {
        try {
            log.info("开始执行手动支付，付款ID: {}", paymentId);

            // 获取付款详情
            PaymentPurchase payment = paymentPurchaseMapper.selectById(paymentId);
            if (payment == null) {
                return R.fail("付款记录不存在");
            }

            // 检查付款状态
            if (payment.getApprovalState() == null || payment.getApprovalState() != 2) {
                return R.fail("付款审批状态不正确，当前审批状态: " + payment.getApprovalState() + "，只有审批通过的记录才能执行手动支付");
            }

            // 执行支付，传递收款人信息
            R payResult = unionPayService.executeSinglePayment(
                payment, 
                payeeName, 
                payeeBankAccount, 
                payeeBankName
            );

            if (payResult.getCode() == 0) {
                // 支付成功
                payment.setState(1); // 1表示实际已付
                payment.setRemitTime(new Date()); // 设置打款时间
                paymentPurchaseMapper.updateById(payment);

                // 查找关联的审批记录并同步状态到企业微信
                try {
                    QueryWrapper<WXApproval> wrapper = new QueryWrapper<>();
                    wrapper.eq("payment_id", paymentId);
                    WXApproval wxApproval = wxApprovalService.getOne(wrapper);
                    
                    if (wxApproval != null) {
                        // 更新审批状态
                        wxApproval.setSpStatus("ALREADY_PAY");
                        wxApprovalService.updateById(wxApproval);
                        
                        // 同步状态到企业微信
                        boolean syncResult = wxApprovalService.syncApprovalStatusToWechat(wxApproval.getSpNo(), "ALREADY_PAY");
                        if (!syncResult) {
                            log.warn("同步审批状态到企业微信失败，审批编号: {}", wxApproval.getSpNo());
                        }
                    }
                } catch (Exception e) {
                    log.warn("同步审批状态时发生异常", e);
                }

                // 发送通知给相关人员
                // notifyApplicant(payment, "手动支付已完成", true);

                log.info("手动支付成功，付款ID: {}", paymentId);
                return R.success("手动支付成功");
            } else {
                // 支付失败
                payment.setState(1); // 1表示实际已付（但支付失败）
                paymentPurchaseMapper.updateById(payment);

                // 发送通知给相关人员
                // notifyApplicant(payment, "手动支付失败: " + payResult.getMsg(), false);

                log.error("手动支付失败，付款ID: {}, 错误信息: {}", paymentId, payResult.getMsg());
                return R.fail("手动支付失败: " + payResult.getMsg());
            }
        } catch (Exception e) {
            log.error("执行手动支付时发生异常", e);
            return R.fail("手动支付异常: " + e.getMessage());
        }
    }
    
    @Override
    public R<Map<String, String>> getPayeeInfoByPaymentId(Long paymentId) {
        try {
            log.info("开始查询付款审批中的收款人信息，付款ID: {}", paymentId);

            // 获取付款详情
            PaymentPurchase payment = paymentPurchaseMapper.selectById(paymentId);
            if (payment == null) {
                return R.fail("付款记录不存在");
            }

            // 初始化收款人信息
            String payeeName = payment.getCustomerName();
            String payeeBankAccount = "";
            String payeeBankName = "";
            
            try {
                // 查找关联的审批记录
                QueryWrapper<WXApproval> wrapper = new QueryWrapper<>();
                wrapper.eq("payment_id", paymentId);
                WXApproval wxApproval = wxApprovalService.getOne(wrapper);
                
                if (wxApproval != null) {
                    // 从企业微信获取审批详情
                    WxCpApprovalDetailResult detailResult = wxCpService.getOaService().getApprovalDetail(wxApproval.getSpNo());
                    if (detailResult != null && detailResult.getErrCode() == 0) {
                        WxCpApprovalDetailResult.WxCpApprovalDetail approvalInfo = detailResult.getInfo();
                        // 使用工具类提取收款人信息
                        Map<String, String> payeeInfo = WxApprovalPayeeInfoExtractor.extractPayeeInfo(approvalInfo);
                        payeeName = payeeInfo.get("payeeName");
                        payeeBankAccount = payeeInfo.get("payeeBankAccount");
                        payeeBankName = payeeInfo.get("payeeBankName");
                    }
                }
            } catch (WxErrorException e) {
                log.warn("从企业微信获取审批详情时发生异常", e);
                return R.fail("从企业微信获取审批详情时发生异常: " + e.getMessage());
            } catch (Exception e) {
                log.warn("解析审批详情中的收款人信息时发生异常", e);
                return R.fail("解析审批详情中的收款人信息时发生异常: " + e.getMessage());
            }
            
            // 构建返回结果
            Map<String, String> payeeInfo = new HashMap<>();
            payeeInfo.put("payeeName", payeeName);
            payeeInfo.put("payeeBankAccount", payeeBankAccount);
            payeeInfo.put("payeeBankName", payeeBankName);
            
            log.info("查询收款人信息成功，付款ID: {}, 收款人全称: {}, 银行账号: {}, 开户行: {}", 
                paymentId, payeeName, payeeBankAccount, payeeBankName);
            
            return R.data(payeeInfo, "查询成功");
        } catch (Exception e) {
            log.error("查询收款人信息时发生异常", e);
            return R.fail("查询收款人信息异常: " + e.getMessage());
        }
    }
}